package com.ami12.shopping.controller;

import com.alibaba.fastjson.JSON;
import com.ami12.shopping.pojo.Item;
import com.ami12.shopping.service.ItemService;
import org.apache.ibatis.reflection.SystemMetaObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * Created by zhangzejun .
 * time: 2016/12/8  9:18
 */
@Controller
@RequestMapping("/item")
public class ItemController {
    @Autowired
    private ItemService itemService;

    @RequestMapping("/list")
    public String selectAll(Model model) throws Exception {
        List<Item> lists= itemService.selectAll();
       // System.out.println(lists);
        model.addAttribute("ItemsList",lists);
        return "item/list";
    }

    @RequestMapping(value = "/ajax",produces = "text/html;charset=UTF-8")
    @ResponseBody
    public  String ajaxTest() throws Exception {
        List<Item> lists= itemService.selectAll();
        System.out.println(lists.getClass());
        //model.addAttribute("ItemsList",lists);
        String jsonString = JSON.toJSONString(lists);
        return jsonString;
    }

    @RequestMapping("/detail/{id}")
    public String selectOne(@PathVariable(value = "id") Integer id,Model model) throws Exception {
        Item item = itemService.selectByPrimaryKey(id);
        model.addAttribute("Item",item);
        System.out.println(item);
        return "item/itemDetail";
    }

    @RequestMapping("/update")
    public String update(HttpServletRequest request,Item item) throws Exception {
        //ModelAndView modelAndView = new ModelAndView();
        //System.out.println(item);
        itemService.updateByPrimaryKey(item);
       // modelAndView.setViewName("/item/list");
        return "redirect:/item/list";
    }
}
